package wechat_server

import (
	"github.com/patrickmn/go-cache"
	"net/http"
	"ssoAndAuth2/oauth2"
	"time"
)

var (
	tokenAuthDuration = time.Minute * 5
	whiteList         = map[string]string{
		"server_a": "http://server_a.com:8080/callback",
		"resource": "http://resource.wechat.com:8082",
	}
)
var authSession = cache.New(tokenAuthDuration, time.Second*30)

type AccessToken struct {
	AccessToken  string  `json:"access_token"`
	ExpiresIn    float64 `json:"expires_in"`    // AccessToken过期时间
	RefreshToken string  `json:"refresh_token"` // 定时刷新AccessToken；当AccessToken过期时，使用RefreshToken刷新AccessToken
}

// ValidateSource 检查签名来源
func ValidateSource(w http.ResponseWriter, r *http.Request) string {
	if err := r.ParseForm(); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = w.Write([]byte(err.Error()))
	}
	signature := r.Form.Get("signature")
	clientId := oauth2.MyEncrypt.Decrypt(signature)
	server := whiteList[clientId]
	if server == "" {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = w.Write([]byte("非法来源"))
	}
	return clientId
}
